package com.dk.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.dk.mapper.TabCategoryMapper;
import com.dk.pojo.TabCategory;
import com.dk.service.CategoryService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.List;

import static java.util.Comparator.comparing;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    TabCategoryMapper tabCategoryMapper;
    @Override
    public List<TabCategory> getInfo() {
        String key = "Route:Category";
        ValueOperations strRedis = redisTemplate.opsForValue();
        Gson gson = new Gson();
        //判断redis是否有分类的key
        if (redisTemplate.hasKey(key)){
            //有就获取数据并返回
            String s = (String) strRedis.get(key);
            List<TabCategory> categories = gson.fromJson(s, new TypeToken<List<TabCategory>>(){}.getType());
            categories.sort(comparing(TabCategory::getCount).reversed());
            /*categories.forEach(q->{
                System.out.println(q.getCount());
            });*/
            return categories;
        }else {
            //没有就从数据库查询
            List<TabCategory> categories = tabCategoryMapper.selectByExample(null);
            categories.sort(comparing(TabCategory::getCount).reversed());
            /*categories.forEach(s->{
                System.out.println(s.getCount());
            });*/
            //存入redis
            String s = gson.toJson(categories);
            strRedis.set(key,s);
            //返回数据
            return categories;
        }
    }

    @Override
    public TabCategory getInfoByCid(Integer cid) {
        return tabCategoryMapper.selectByPrimaryKey(cid);
    }
}
